REG_EXT = /\.[a-z]+/ #用于匹配后缀名的正则表达式
#参与链接的源文件
srcs = ["init0.asm", "init1.c"]
objs = srcs.map {|x| x.gsub(REG_EXT, ".o")}

file "boot.bin" => "boot.asm" do |t|
    sh "nasm -f bin boot.asm -o boot.bin"
end

(0...srcs.size).each do |i|
    src = srcs[i]
    obj = objs[i]
    file obj => src do |t|
        REG_EXT.match(src)
        if $~[0] == ".c"
            sh "gcc -c #{src} -m32 -nostdinc -ffreestanding -o #{obj}"
        elsif $~[0] == ".asm"
            sh "nasm -f elf32 #{src} -o #{obj}"
        end
    end
end

file "init.bin" => objs do |t|
    sh "ld -o init.elf -Ttext 0x0 -e init0_start #{objs.join(' ')}"
    sh "objcopy -R .note -R .comment -S -O binary init.elf init.bin"
end

task :build do |t|
    Rake::Task["boot.bin"].invoke   #生成boot.bin
    objs.each {|obj| Rake::Task[obj].invoke } #生成所有的.o文件
    Rake::Task["init.bin"].invoke   #生成init.bin
end

task :clean do |t|
    sh "del *.bin"
    sh "del *.elf"
    sh "del *.o"
end

